﻿using AutojsController.Config;
using AutojsController.Helpers;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading;
using System.Threading.Tasks;

namespace AutojsController.Services
{
    public class GroupsService: IDBService
    {
        public GroupsService(IDbContextFactory<Config.DBContext> dbContextFactory) : base(dbContextFactory)
        {
        }

        public async Task<List<Group>> getAllGroupsAsync()
        {
            using var db = await dbFactory.CreateDbContextAsync();
            return await db.groups.ToListAsync();
        }

        public async Task<Group?> GetByGroupIdAsync(int Id)
        {
            using var db = await dbFactory.CreateDbContextAsync();
            return await db.groups.FindAsync(Id);
        }

        public async Task<bool> RenameAsync(int Id, string newName)
        {
            using var db = await dbFactory.CreateDbContextAsync();
            var grp = await db.groups.FindAsync(Id);
            if (grp == null) return false;
            grp.Name = newName;
            await db.SaveChangesAsync();
            return true;
        }

        public async Task<Group> AddGroupAsync(string name, int? scriptId)
        {
            using var db = await dbFactory.CreateDbContextAsync();
            if (await db.groups.CountAsync() > Consts.MAX_GROUP_COUNT)
                throw new GroupCountLimitExceededException($"超过分组上限{Consts.MAX_GROUP_COUNT}个");
            var exist = await db.groups.Where(g => g.Name == name).CountAsync() > 0;
            if (exist) throw new DuplicateGroupException(name);
            var grp = new Group(){ Name = name, ScriptID = scriptId };
            db.groups.Add(grp);
            await db.SaveChangesAsync();
            return grp;
        }

        public async Task DeleteGroupAsync(int groupId)
        {
            using var db = await dbFactory.CreateDbContextAsync();
            await db.groups.Where(g => g.Id == groupId).ExecuteDeleteAsync();
        }
    }
}
